package com.ebupt.migu.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import sun.rmi.runtime.Log;

import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Map;

/**
 * @author tz
 */
@Slf4j
public class RestHttpUtil {


    /**
     *  get请求
     * @param url
     * @param map
     * @return
     */
    public static String doGet(String url, Map<String,Object> map){
        try {
            RestTemplate restTemplate = getRestTemplate();
            //发送请求
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);
            return responseEntity.getBody() == null ? "GET request error!":responseEntity.getBody();
        }catch (GeneralSecurityException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  post请求
     * @param url
     * @param obj
     * @return
     */
    public static String doPost (String url,Object obj){

        try {
            RestTemplate restTemplate = getRestTemplate();
            //设置header参数（根据实际情况修改或添加）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //请求实体
            HttpEntity<Object> entity = new HttpEntity<>(JSON.toJSON(obj), headers);
            //发送请求
            log.info(">>>>>>>>>>>>>>>>url:{},entity:{}",url,entity.toString());
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
            return responseEntity.getBody() == null ? "POST request error!":responseEntity.getBody();
        }catch (GeneralSecurityException e){
            e.printStackTrace();
        }
        return null;

    }

    @Bean
    public static RestTemplate getRestTemplate() throws GeneralSecurityException {

        TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
        BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setConnectionManager(connectionManager).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        //参数设置
        requestFactory.setConnectTimeout(1000);
        requestFactory.setReadTimeout(1000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        //设置编码集
        //restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        restTemplate.getMessageConverters().clear();
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        return restTemplate;
    }

}
